package com.baiyang.app.tool;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LogUtils {
    private String path;
    private LogUtils(){}
    private static LogUtils logUtils = new LogUtils();
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.CANADA);
    public static LogUtils getLogUtils(){
        return logUtils;
    }
    public void setPath(String path){
        this.path = path;
    }

    public static int i(String tag, String msg){
        logUtils.writeLocal(tag,msg);
        return Log.i(tag,msg);
    }

    //开启线程进行上传照片   --- 创建一个无边界的线程池
    ExecutorService executor = Executors.newFixedThreadPool(1);
    /**
     * 将log写入本地
     */
    private void writeLocal(String tag, String msg){
        executor.submit(new MyThread(tag,msg));
    }

    private class MyThread extends Thread{
        private String tag;
        private String msg;
        public MyThread(String tag,String msg){
            this.msg = msg;
            this.tag = tag;
        }
        @Override
        public void run() {
            FileOutputStream outputStream = null;
            BufferedOutputStream bof = null;
            try{
                File file = new File(path + sdf.format(new Date()) + ".log");
                if(!file.exists()){
                    file.createNewFile();
                }
                outputStream = new FileOutputStream(file,true);
                bof = new BufferedOutputStream(outputStream);
                String str = tag + ":" + msg + "\n";
                bof.write(str.getBytes(),0,str.getBytes().length);
                bof.flush();
                bof.close();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    bof.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
